/**
 * 演示数据生成脚本
 * 用于创建系统演示所需的测试数据
 */

const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');

// 连接数据库
const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://admin:password123@localhost:27017/tea_traceability?authSource=admin';

// 禁用Mongoose缓冲
mongoose.set('bufferCommands', false);

// 设置Mongoose连接事件监听
mongoose.connection.on('connected', () => {
  console.log('Mongoose 连接到 MongoDB');
});

mongoose.connection.on('error', (err) => {
  console.error('Mongoose 连接错误:', err);
});

mongoose.connection.on('disconnected', () => {
  console.log('Mongoose 连接断开');
});

// 导入实际的模型
const User = require('../backend/src/models/User');
const TeaBatch = require('../backend/src/models/TeaBatch');

// 演示用户数据
const demoUsers = [
  {
    username: 'admin',
    email: 'admin@teatrace.com',
    password: 'admin123',
    role: 'admin',
    address: '0x742d35cc6e60e6ea92d5d0d8b6c4e4a6f1b8f9c1'
  },
  {
    username: 'farmer_zhang',
    email: 'zhang@farm.com',
    password: 'farmer123',
    role: 'farmer',
    address: '0x8ba1f109551bd432803012645fac136c69c1e3d1'
  },
  {
    username: 'logistics_li',
    email: 'li@logistics.com',
    password: 'logistics123',
    role: 'logistics',
    address: '0x4838b106fce9c325fcdd5a30c40a12f5e8e4a9b2'
  },
  {
    username: 'merchant_wang',
    email: 'wang@shop.com',
    password: 'merchant123',
    role: 'merchant',
    address: '0x9f8a5c22b345c2789d4a8f1e5e3c4b6a7d8e9f10'
  },
  {
    username: 'consumer_liu',
    email: 'liu@email.com',
    password: 'consumer123',
    role: 'consumer',
    address: '0x1234567890abcdef1234567890abcdef12345678'
  }
];

// 演示批次数据（使用TeaBatch模型的字段结构）
const demoBatches = [
  {
    batchId: 'TEA2024001',
    name: '西湖龙井精品茶',
    variety: '龙井茶',
    grade: '特级',
    description: '来自杭州西湖核心产区的优质龙井茶',
    status: 'sales',
    production: {
      origin: {
        province: '浙江省',
        city: '杭州市',
        county: '西湖区',
        village: '龙井村'
      },
      harvestDate: new Date('2024-03-15'),
      processingMethod: '传统手工炒制',
      processingDate: new Date('2024-03-16'),
      weight: 100,
      qualityGrade: '特级'
    }
  },
  {
    batchId: 'TEA2024002',
    name: '安溪铁观音',
    variety: '铁观音',
    grade: '一级',
    description: '福建安溪传统工艺制作的铁观音',
    status: 'logistics',
    production: {
      origin: {
        province: '福建省',
        city: '泉州市',
        county: '安溪县',
        village: '感德镇'
      },
      harvestDate: new Date('2024-04-20'),
      processingMethod: '传统乌龙茶工艺',
      processingDate: new Date('2024-04-21'),
      weight: 150,
      qualityGrade: '一级'
    }
  },
  {
    batchId: 'TEA2024003',
    name: '云南普洱',
    variety: '普洱茶',
    grade: '二级',
    description: '云南大叶种晒青毛茶制作的普洱茶',
    status: 'production',
    production: {
      origin: {
        province: '云南省',
        city: '昆明市',
        county: '西山区',
        village: '碧鸡镇'
      },
      harvestDate: new Date('2024-05-10'),
      processingMethod: '晒青工艺',
      processingDate: new Date('2024-05-12'),
      weight: 200,
      qualityGrade: '二级'
    }
  }
];

// 数据库连接函数，支持重试
async function connectToDatabase(maxRetries = 5) {
  let retries = 0;
  
  while (retries < maxRetries) {
    try {
      console.log(`🔗 尝试连接数据库... (${retries + 1}/${maxRetries})`);
      
      await mongoose.connect(MONGODB_URI, {
        serverSelectionTimeoutMS: 60000,  // 增加到60秒服务器选择超时
        connectTimeoutMS: 60000,          // 增加到60秒连接超时
        socketTimeoutMS: 60000,           // 增加到60秒socket超时
        maxPoolSize: 1,                   // 最大连接池大小
        retryWrites: true,                // 启用重试写入
        heartbeatFrequencyMS: 10000,      // 心跳频率
        maxIdleTimeMS: 30000,             // 最大空闲时间
        family: 4                         // 强制使用IPv4
      });
      
      console.log('✅ 数据库连接成功');
      return;
      
    } catch (error) {
      retries++;
      console.error(`❌ 数据库连接失败 (尝试 ${retries}/${maxRetries}):`, error.message);
      
      if (retries >= maxRetries) {
        throw new Error(`数据库连接失败，已重试 ${maxRetries} 次: ${error.message}`);
      }
      
      const waitTime = Math.min(retries * 2000, 10000); // 递增等待时间，最多10秒
      console.log(`⏰ 等待 ${waitTime/1000} 秒后重试...`);
      await new Promise(resolve => setTimeout(resolve, waitTime));
    }
  }
}

// 数据库初始化函数
async function initializeDatabase() {
  try {
    // 连接数据库（使用重试机制）
    await connectToDatabase();
    
    // 等待连接稳定
    console.log('⏳ 等待连接稳定...');
    await new Promise(resolve => setTimeout(resolve, 5000)); // 增加到5秒

    // 验证数据库连接状态
    console.log('🔍 验证数据库连接状态...');
    const dbState = mongoose.connection.readyState;
    console.log(`   数据库状态: ${dbState === 1 ? '已连接' : '未连接'}`);
    
    if (dbState !== 1) {
      throw new Error('数据库连接状态异常');
    }

    // 先测试数据库基本功能
    console.log('🔍 测试数据库基本功能...');
    try {
      await mongoose.connection.db.admin().ping();
      console.log('   ✅ 数据库ping成功');
    } catch (error) {
      console.error('   ❌ 数据库ping失败:', error.message);
      throw error;
    }

    // 检查现有数据，使用更简单的方法
    console.log('🔍 检查现有数据...');
    let existingUsers = 0, existingBatches = 0;
    
    try {
      // 使用原生MongoDB驱动进行查询，避免Mongoose缓冲问题
      const db = mongoose.connection.db;
      existingUsers = await db.collection('users').countDocuments();
      existingBatches = await db.collection('teabatches').countDocuments();
      console.log(`ℹ️  现有用户: ${existingUsers}, 现有批次: ${existingBatches}`);
    } catch (error) {
      console.error('查询现有数据失败:', error.message);
      // 不抛出错误，继续执行
      console.log('   继续执行数据创建...');
    }

    // 创建演示用户 - 使用原生MongoDB驱动避免Mongoose缓冲问题
    console.log('👥 创建演示用户...');
    const createdUsers = [];
    const db = mongoose.connection.db;
    
    for (const userData of demoUsers) {
      try {
        // 使用原生驱动检查用户是否存在
        const existingUser = await db.collection('users').findOne({ email: userData.email });
        
        if (!existingUser) {
          // 使用Mongoose模型创建用户（触发中间件如密码加密）
          const user = new User(userData);
          const savedUser = await user.save();
          createdUsers.push(savedUser);
          console.log(`   ✓ 创建用户: ${savedUser.username} (${savedUser.role})`);
        } else {
          // 直接使用原生文档，避免Mongoose查询
          createdUsers.push(existingUser);
          console.log(`   ℹ️  用户已存在: ${existingUser.username} (${existingUser.role})`);
        }
      } catch (error) {
        console.error(`   ❌ 用户操作失败 (${userData.username}):`, error.message);
        
        // 如果Mongoose save失败，尝试直接插入
        if (error.message.includes('buffering timed out') || error.message.includes('timeout')) {
          try {
            console.log(`   🔄 尝试直接插入用户: ${userData.username}`);
            // 手动加密密码
            const bcrypt = require('bcryptjs');
            const saltRounds = 12;
            const hashedPassword = await bcrypt.hash(userData.password, saltRounds);
            
            const userToInsert = {
              ...userData,
              password: hashedPassword,
              createdAt: new Date(),
              updatedAt: new Date(),
              status: 'active',
              emailVerified: false,
              loginAttempts: 0,
              refreshTokens: []
            };
            
            const result = await db.collection('users').insertOne(userToInsert);
            const insertedUser = await db.collection('users').findOne({ _id: result.insertedId });
            createdUsers.push(insertedUser);
            console.log(`   ✓ 直接创建用户: ${userData.username} (${userData.role})`);
          } catch (insertError) {
            console.error(`   ❌ 直接插入也失败: ${insertError.message}`);
            throw insertError;
          }
        } else {
          throw error;
        }
      }
    }

    // 创建演示批次 - 使用原生MongoDB驱动避免缓冲问题
    console.log('📦 创建演示批次...');
    const farmer = createdUsers.find(u => u.role === 'farmer');
    
    if (!farmer) {
      throw new Error('未找到农民用户，无法创建批次');
    }
    
    const farmerId = farmer._id || farmer.id;
    const farmerAddress = farmer.address;
    
    for (const batchData of demoBatches) {
      try {
        // 使用原生驱动检查批次是否存在
        const existingBatch = await db.collection('teabatches').findOne({ batchId: batchData.batchId });
        
        if (!existingBatch) {
          // 直接使用原生驱动插入批次数据
          const batchToCreate = {
            batchId: batchData.batchId,
            name: batchData.name,
            variety: batchData.variety,
            grade: batchData.grade,
            description: batchData.description,
            status: batchData.status,
            currentStage: 'production',
            createdBy: farmerId,
            isPublic: true,
            views: 0,
            logistics: [],
            sales: [],
            images: [],
            totalTransactions: 0,
            // 修正production字段结构以匹配模型
            production: {
              farmerId: farmerId,
              farmerAddress: farmerAddress,
              origin: batchData.production.origin,
              harvestDate: batchData.production.harvestDate,
              processingMethod: batchData.production.processingMethod,
              recordedAt: new Date()
            },
            createdAt: new Date(),
            updatedAt: new Date()
          };
          
          const result = await db.collection('teabatches').insertOne(batchToCreate);
          console.log(`   ✓ 创建批次: ${batchData.batchId} (${batchData.name})`);
        } else {
          console.log(`   ℹ️  批次已存在: ${existingBatch.batchId} (${existingBatch.name})`);
        }
      } catch (error) {
        console.error(`   ❌ 批次操作失败 (${batchData.batchId}):`, error.message);
        
        // 如果直接插入失败，记录错误但继续执行
        if (error.message.includes('timeout') || error.message.includes('buffering')) {
          console.log(`   ⚠️  跳过批次 ${batchData.batchId}，继续下一个...`);
          continue;
        } else {
          throw error;
        }
      }
    }
 
  } catch (error) {
    console.error('❌ 演示数据创建失败:', error);
    process.exit(1);
  } finally {
    await mongoose.connection.close();
    console.log('🔐 数据库连接已关闭');
  }
}

// 如果直接运行此脚本，则执行数据库初始化
if (require.main === module) {
  initializeDatabase();
}

module.exports = { initializeDatabase };